package jmeter.javarequest;

import com.google.gson.Gson;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author evoup
 * opentsdb压测
 */
public class JavaRequestOpenTsdbBench extends AbstractJavaSamplerClient {
    private static CloseableHttpClient httpClient;

    @Override
    public Arguments getDefaultParameters() {
        return super.getDefaultParameters();
    }

    @Override
    public void setupTest(JavaSamplerContext context) {
        super.setupTest(context);
    }

    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult result = new SampleResult();
        boolean success = false;
        result.sampleStart();
        httpClient = HttpClients.createDefault();
        long startTime = System.currentTimeMillis();
        List<Object> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        Map<String, String> tags = new HashMap<>();
        tags.put("operationValue", "HDFF88FFF");
        tags.put("gateMac", "00E2690CDFFD");
        map.put("metric", 10);
        map.put("value", "100");
        map.put("tags", tags);
        map.put("timestamp", startTime / 1000 + 3000000);
        list.add(map);
        try {
            sendPost(list);
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            result.sampleEnd();
            result.setSuccessful(success);
            list.clear();
        }


        return result;
    }

    private static void sendPost(List<Object> list) throws IOException {
        final HttpPost httpPost = new HttpPost("http://data-collector:14242/api/put?async");
        if (!list.isEmpty()) {
            String string = new Gson().toJson(list);
            StringEntity entity = new StringEntity(string, "utf-8");
            entity.setContentEncoding("utf-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpClient.execute(httpPost);
        }
    }
}
